<template>
	<view class="setting-box">
		<view>
			<image src="/static/images/left.png" class="left-icon" @click="backToLast"></image>
		</view>
		<!-- 信息展示 -->
		<view class="top-box">
			<view>
				<image src="/static/images/logo.png" class="avatar-style" alt="avatar"></image>

				<view v-if="isPhone" class="title-style">
					<!-- 绑定手机号 -->
					<view v-if="!havePhone">{{$t("actionBindPhone")}}</view>
					<!-- 修改手机号 -->
					<view v-else>{{$t("editPhone")}}</view>
				</view>
				<view v-else-if="isEmail" class="title-style">
					<!-- 绑定邮箱 -->
					<view v-if="!haveEmail">{{$t("actionBindEmail")}}</view>
					<!-- 修改邮箱 -->
					<view v-else>{{$t("editEmail")}}</view>
				</view>
				<view v-else class="title-style">{{$t("changePassword")}}</view>
			</view>
		</view>
		<view style="background-color: #fff;height: 100%;">
			<up-form :model="formData" :rules="validationRules" ref="formRef" errorType="none">
				<!-- 手机号input -->
				<view v-if="isPhone" style="text-align: center;">
					<up-form-item prop="phone" ref="phoneRef" style="width: 80%;margin: 0 auto;">
						<up-input class="input-style" v-model="formData.phone" border="surround"
							:placeholder="$t('bindPhonePlaseholder')"></up-input>
					</up-form-item>
					<!-- 验证码input -->
					<up-form-item prop="code" ref="codeRef" style="width: 80%;margin: 0 auto;position: relative;">
						<up-input class="input-style" v-model="formData.code" border="surround"
							:placeholder="$t('phoneCodePlaseholder')"></up-input>
						<view class="send-code-btn" ref="uToastRef" @tap="getCodePhone">{{tips}}</view>
						<up-code :seconds="seconds" ref="uCodeRef" @change="codeChange" @end="end" @start="start"
							change-text="XS" :startText="$t('getCode')" :endText="$t('getAgain')"
							:keepRunning="true"></up-code>
					</up-form-item>
				</view>
				<!-- 邮箱号input -->
				<view v-else-if="isEmail" style="text-align: center;">
					<up-form-item prop="email" ref="emailRef" style="width: 80%;margin: 0 auto;">
						<up-input class="input-style" v-model="formData.email" border="surround"
							:placeholder="$t('bindEmailPlaseholder')"></up-input>
					</up-form-item>
					<!-- 验证码input -->
					<up-form-item prop="code" ref="codeRef" style="width: 80%;margin: 0 auto;position: relative;">
						<up-input class="input-style" v-model="formData.code" border="surround"
							:placeholder="$t('emailCodePlaseholder')"></up-input>
						<view class="send-code-btn" ref="uToastRef" @tap="getCodeEmail">{{tips}}</view>
						<up-code :seconds="seconds" ref="uCodeRef" @change="codeChange" @end="end" @start="start"
							change-text="XS" :startText="$t('getCode')" :endText="$t('getAgain')"
							:keepRunning="true"></up-code>
					</up-form-item>
				</view>

				<!-- 修改密码 -->
				<view v-if="!isPhone && !isEmail" style="text-align: center;">
					<up-form-item prop="oldPassword" ref="passwordRef0"
						style="width: 80%;margin: 0 auto;position: relative;">
						<up-input :password="!passShow1" class="input-style" v-model="formData.oldPassword"
							border="surround" :placeholder="$t('updatePasswordPlaseholder0')"></up-input>
						<view class="eyeBox">
							<up-icon name="eye-fill" size="22" v-if="passShow1"
								@click="passShow1 = !passShow1"></up-icon>
							<up-icon name="eye-off" size="22" v-else @click="passShow1 = !passShow1"></up-icon>
						</view>
					</up-form-item>
					<up-form-item prop="password" ref="passwordRef1"
						style="width: 80%;margin: 0 auto;position: relative;">
						<up-input :password="!passShow2" class="input-style" v-model="formData.password"
							border="surround" :placeholder="$t('updatePasswordPlaseholder1')"></up-input>
						<view class="eyeBox">
							<up-icon name="eye-fill" size="22" v-if="passShow2"
								@click="passShow2 = !passShow2"></up-icon>
							<up-icon name="eye-off" size="22" v-else @click="passShow2 = !passShow2"></up-icon>
						</view>
					</up-form-item>
					<up-form-item prop="password2" ref="passwordRef2"
						style="width: 80%;margin: 0 auto;position: relative;">
						<up-input :password="!passShow3" class="input-style" v-model="formData.password2"
							border="surround" :placeholder="$t('updatePasswordPlaseholder2')"
							:keepRunning="true"></up-input>
						<view class="eyeBox">
							<up-icon name="eye-fill" size="22" v-if="passShow3"
								@click="passShow3 = !passShow3"></up-icon>
							<up-icon name="eye-off" size="22" v-else @click="passShow3 = !passShow3"></up-icon>
						</view>
					</up-form-item>
					<view style="color: #818181;font-size: 13px;margin-bottom: 0.4rem;">
						{{$t('passwordTip')}}
					</view>
					<view style="color: #1a1a1a;font-size: 15px;font-weight: ;" @click="toResetPwd()">
						{{$t('forgetPwd')}}
					</view>
				</view>
			</up-form>

			<!-- 按钮 -->
			<view v-if="isPhone">
				<button class="submit-btn" @click="submitPhone()">{{$t('submit')}}</button>
			</view>
			<view v-else-if="isEmail">
				<button class="submit-btn" @click="submitEmail()">{{$t('submit')}}</button>
			</view>
			<view v-if="!isPhone && !isEmail">
				<button class="submit-btn" style="margin-top: 0.5rem;"
					@click="submitPassword()">{{$t('submit')}}</button>
			</view>
		</view>
	</view>
	<up-toast ref="uToastRef"></up-toast>
	<up-toast ref="uToastRef2"></up-toast>

	<upModal :modalWidth="'15rem'" :modalShow="modalShow" :modalText1="modalText1" :showImage="true" :isCancel="false"
		:isAgreement="false" :isAgreement2="false" @cancel="cancel" @cloos="cloos">
	</upModal>
</template>

<script setup lang="ts">
	import { computed, ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { useI18n } from 'vue-i18n'
	import { getPhoneCode, getEmailCode } from "@/api/login.js"
	import { setPhone, setEmail, setPassword } from "@/api/setting/setting.js"
	import upModal from '../../components/upModal.vue'

	const { t } = useI18n()
	const isPhone = ref(false)
	const isEmail = ref(false)

	const tips = ref('');
	const uCodeRef = ref(null);
	const seconds = ref(60);
	const codeChange = (text) => {
		tips.value = text;
	};

	// 定义表单数据类型
	interface FormDataType {
		phone ?: string
		email ?: string
		code ?: string
		password ?: string
		password2 ?: string
		oldPassword ?: string
	}
	// 初始化表单数据
	const oldPhone = ref("")
	const oldEmail = ref("")
	const formData = ref<FormDataType>({})
	const formRef = ref(null)
	const havePhone = ref(false)  //已绑定手机号  显示修改手机号
	const haveEmail = ref(false)  //已绑定Email  显示修改Email
	const passShow1 = ref(false)
	const passShow2 = ref(false)
	const passShow3 = ref(false)

	const modalShow = ref(false) // 弹窗显示状态
	const modalText1 = ref('') // 弹窗内容
	const cancel = () => {
		modalShow.value = false
	}
	const cloos = () => {
		modalShow.value = false
		if (modalText1.value == t('setPwdSuccess')) {
			//跳转到登录页
			uni.navigateTo({
				// url: '/pages/setting/settingInfo',
				url: '/pages/login/login'
			})
			// 清除缓存
			uni.removeStorageSync('token')
			uni.setStorageSync('refreshToken', '')
			uni.setStorageSync('accessTokenExp', '')
			uni.setStorageSync('avatarUrl', '')
			uni.setStorageSync('username', '')
			uni.setStorageSync('userCode', '')
			uni.setStorageSync('dplID', '')
			uni.removeStorageSync('lang');
			uni.setStorageSync('userPhone', '')
		}else if(modalText1.value == t('bindPhoneSuccess')){
			// 返回个人信息页
			uni.navigateTo({
				url: '/pages/setting/settingInfo'
			})
		}
	}

	onLoad((options : { phone ?: string, email ?: string }) => {
		// 获取 URL 参数中的 phone
		if (Object.prototype.hasOwnProperty.call(options, 'phone')) {
			// formData.value.phone = options.phone || '' // 空值也赋值
			oldPhone.value = options.phone || '' // 空值也赋值
			formData.value.phone = ''
			if (options.phone != '') {
				havePhone.value = true
			}
			isPhone.value = true
		}

		// 获取 URL 参数中的 email
		if (Object.prototype.hasOwnProperty.call(options, 'email')) {
			formData.value.email = '' // 空值也赋值
			oldEmail.value = options.email || '' // 空值也赋值
			if (options.email != '') {
				haveEmail.value = true
			}
			isEmail.value = true
		}
		else {
			formData.value.password = ''
			formData.value.password2 = ''
		}
	})
	// 表单验证规则
	const validationRules = computed(() => ({
		phone: [
			{ required: isPhone.value, message: t('bindPhonePlaseholder'), trigger: 'blur' },
			{ min: 11, max: 11, message: t('phoneLengthError'), trigger: 'blur' },
			{ pattern: /^1[3-9]\d{9}$/, message: t('phoneIncorrectFormat'), trigger: 'blur' }
		],
		email: [
			{ required: !isPhone.value, message: t('bindEmailPlaseholder'), trigger: 'blur' },
			{ type: 'email', message: t('emailIncorrectFormat'), trigger: 'blur' }
		],
		code: [
			{ required: true, message: t('inputCaptcha'), trigger: 'blur' },
			{ min: 6, max: 6, message: t('captchaLengthError'), trigger: 'blur' }
		],
		oldPassword: [
			// { required: !isPhone.value && !isEmail.value, message: t('palceInputPassword'), trigger: 'blur' },
			{ min: 8, message: t('passwordLengthError'), trigger: 'blur' }
		],
		password: [
			{ required: !isPhone.value && !isEmail.value, message: t('palceInputPassword'), trigger: 'blur' },
			{ min: 8, message: t('passwordLengthError'), trigger: 'blur' }
		],
		password2: [
			{ required: !isPhone.value && !isEmail.value, message: t('inputPasswordAgain'), trigger: 'blur' },
			{ min: 8, message: t('passwordLengthError'), trigger: 'blur' },
			{
				validator: (rule, value) => {
					if (value !== formData.value.password) {
						return new Error(t('passwordNotSame'));
					}
					return true;
				},
				trigger: 'blur'
			}
		]
	}))

	const backToLast = () => {
		uni.navigateBack()
	}
	// 获取手机验证码
	const getCodePhone = () => {
		const phonePattern = /^1[3-9]\d{9}$/;
		if (formData.value.phone && phonePattern.test(formData.value.phone)) {
			if (uCodeRef.value.canGetCode) {
				uni.showLoading({
					title: t('gettingCode'),
				});
				getPhoneCode({ phone: formData.value.phone }).then((res) => {
					if (res && res.code === 200) {
						uni.hideLoading();
						// 通知验证码组件内部开始倒计时
						uCodeRef.value.start();
					} else {
						uni.hideLoading();
						uni.showToast({
							title: t('getCodeFailed'), // 新增获取验证码失败提示文案，需在国际化文件中定义
							icon: 'none',
							duration: 1500
						});
					}
				})
			} else {
				uni.showToast({
					title: t('NotEnd'),
					icon: 'none',
					duration: 1000
				})
			}
		} else {
			modalShow.value = true
			if(formData.value.phone.length!=11){
				modalText1.value= t('phoneLengthError')
			}else{
				modalText1.value= t('phoneIncorrectFormat')
			}
			// uni.showToast({
			// 	title: t('phoneIncorrectFormat'),
			// 	icon: 'none',
			// 	duration: 1000
			// });
		}
	}
	// 获取邮箱验证码
	const getCodeEmail = () => {
		const emailPattern = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
		if (formData.value.email && emailPattern.test(formData.value.email)) {
			if (uCodeRef.value.canGetCode) {
				uni.showLoading({
					title: t('gettingCode'),
				});
				getEmailCode(formData.value.email).then((res) => {
					if (res && res.code === 200) {
						uni.hideLoading();
						// uni.showToast({
						// 	title: t('haveSendCode'),
						// 	icon: 'none',
						// 	duration: 1500
						// });
						// 通知验证码组件内部开始倒计时
						uCodeRef.value.start();
					} else {
						uni.hideLoading();
						uni.showToast({
							title: t('getCodeFailed'), // 新增获取验证码失败提示文案，需在国际化文件中定义
							icon: 'none',
							duration: 1500
						});
					}
				})
			} else {
				uni.showToast({
					title: t('NotEnd'),
					icon: 'none',
					duration: 1000
				})
			}
		} else {
			uni.showToast({
				title: t('emailIncorrectFormat'),
				icon: 'none',
				duration: 1000
			})
		}
	}
	const end = () => {
		// uni.$u.toast('倒计时结束');
	};
	const start = () => {
		uni.showToast({
			title: t('haveSendCode'),
			icon: 'none',
			duration: 1000
		})
	};
	function toResetPwd() {
		uni.navigateTo({
			//resetPassword 忘记密码页
			url: '/pages/login/ForgotPassword'
		})
	}
	const uToastRef = ref(null)
	const uToastRef2 = ref(null)
	// 提交
	function submitPhone() {
		formRef.value.validateField(['phone', 'code'], (errors : any) => {
			// errors 为校验结果，若为空则表示校验通过
			if (Object.keys(errors).length === 0) {
				// 调接口
				setPhone({ phone: formData.value.phone, msg: formData.value.code }).then((res) => {
					if (res && res.code === 200) {
						modalShow.value = true
						modalText1.value= t('bindPhoneSuccess')
					} else {
						// uToastRef2.value.show({
						// 	type: 'default',
						// 	message: res.msg
						// });
						modalShow.value = true
						if(res.code === 10102003){// 验证码错误
							modalText1.value= t('Captchaerrorenteragain')
						}else if (res.code === 10102002) {// 未发送验证码或者已过期
							modalText1.value= t('notSendOrExpire')
						}else if (res.code === 11115) {// 该电话号码已被绑定
							modalText1.value= t('phoneHaveBound')
						}else{
							modalText1.value=res.msg
						}
					}
				})
			} else {
				// 校验不通过，可遍历 errors 提示用户（或简单提示“表单有误”）
				console.error('验证失败:', errors)
				// uToastRef2.value.show({
				// 	type: 'default',
				// 	message: errors[0].message
				// });
				modalShow.value = true
				modalText1.value= errors[0].message
			}
		});

	}
	function submitEmail() {
		if (oldEmail.value && formData.value.email == oldEmail.value) {
			uni.showToast({
				// 邮箱号相同，无需绑定
				title: t('emailSame'),
				icon: 'none',
				duration: 1000
			});
		} else if (formData.value.email == '' || formData.value.email == undefined) {
			uni.showToast({
				title: t('inputEmail'),
				icon: 'none',
				duration: 1000
			});
		} else if (formData.value.code == '' || formData.value.code == undefined) {
			uni.showToast({
				title: t('inputEmailCaptcha'),
				icon: 'none',
				duration: 1000
			});
		}
		else {
			// 调接口
			setEmail({ email: formData.value.email, msg: formData.value.code }).then((res) => {

				if (res && res.code === 200) {
					// uni.showToast({
					// 	title: res.msg,
					// 	icon: 'none',
					// 	duration: 1500
					// })
					// 返回个人信息页
					uni.navigateTo({
						url: '/pages/setting/settingInfo'
					})
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 1500
					});
				}
			})
		}
	}
	function submitPassword() {
		// 仅校验密码相关字段：oldPassword、password、password2
		formRef.value.validateField(['oldPassword', 'password', 'password2'], (errors : any) => {
			// errors 为校验结果，若为空则表示校验通过
			if (Object.keys(errors).length === 0) {
				// 调接口（这里可去掉重复的空值判断，因为校验已处理）
				if (formData.value.oldPassword === '' || formData.value.oldPassword === undefined) {
					formData.value.oldPassword = '';
				}
				console.log("点击了222", formData.value.password, formData.value.password2, formData.value.oldPassword);
				setPassword({
					passWord: formData.value.password,
					passWord2: formData.value.password2,
					oldPassWord: formData.value.oldPassword,
				}).then((res) => {
					if (res && res.code === 200) {
						// 设置密码成功
						modalShow.value = true
						modalText1.value = t('setPwdSuccess')
						// uToastRef.value.show({
						// 	type: 'default',
						// 	message: t('setPwdSuccess')
						// });
					} else {
						modalShow.value = true
						if (res.code == 10102017) {  //新旧密码一样
							modalText1.value = t('newAndOldSame')
						} else if(res.code == 10102019){  //原密码错误
							modalText1.value = t('oldPwdIncorrect')
						}
						else {
							modalText1.value = res.msg
						}
						// uToastRef.value.show({
						// 	type: 'default',
						// 	message: res.msg
						// });
					}
				})
			} else {
				// 校验不通过，可遍历 errors 提示用户（或简单提示“表单有误”）
				console.error('验证失败:', errors)
				// uToastRef.value.show({
				// 	type: 'default',
				// 	message: errors[0].message
				// });
				modalShow.value = true
				modalText1.value = errors[0].message
			}
		});
	}
</script>

<style lang="scss" scoped>
	.setting-box {
		width: 100%;
		height: 100%;
		/*微信小程序无法使用本地资源图片作为背景图 使用base64格式*/
		background-image: url('');
		background-size: cover;
		background-repeat: no-repeat;
		box-sizing: border-box;
		padding: 2rem 0;
		/* #ifdef  MP-WEIXIN*/
		padding-top: 3.5rem;
		/* #endif*/
	}

	.left-icon {
		width: 1.5rem;
		height: 1.5rem;
		margin: 0rem 0 0 0.5rem;
		/* #ifdef  MP-WEIXIN*/
		margin: 0rem 0 0 0.5rem;
		/* #endif*/
	}

	.top-box {
		width: 100%;
		/* height: 11rem;*/
		background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%);
		position: relative;
		text-align: center;
	}

	.avatar-style {
		width: 8.38rem;
		height: 8.38rem;
		border-radius: 50%;
	}

	.title-style {
		height: 1.5rem;
		line-height: 1.5rem;
		color: rgba(16, 16, 16, 0.8);
		font-size: 0.88rem;
		font-weight: 600;
		text-align: center;
		/* margin-bottom: 1rem;*/
	}

	.input-style {
		height: 1.8rem;
		line-height: 1.8rem;
		border-radius: 0.94rem;
		background-color: rgba(0, 0, 0, 0.05);
		color: rgba(136, 136, 136, 1);
		border: 1px solid #ccc;
		font-size: 0.88rem;
	}

	.eyeBox {
		position: absolute;
		right: 20rpx;
	}

	/* 自定义验证码输入框的样式 */
	.send-code-btn {
		position: absolute;
		right: 0;
		width: 5rem;
		height: 1.8rem;
		line-height: 1.8rem;
		padding: 6px 0;
		border-radius: 0rem 0.94rem 0.94rem 0rem;
		background-color: rgba(255, 255, 255, 1);
		color: rgba(16, 16, 16, 0.6);
		font-size: 0.88rem;
		border: 0.03rem solid rgba(187, 187, 187, 1);
	}

	.submit-btn {
		width: 80%;
		height: 2.8rem;
		line-height: 2.8rem;
		border-radius: 0.5rem;
		background-color: rgba(222, 134, 143, 1);
		color: #fff;
		font-size: 0.88rem;
		text-align: center;
		margin-top: 2rem;
		border: none;
	}

	/* 使用 :deep 确保样式穿透  校验文字居中*/
	:deep(.u-form-item__body__right__message) {
		margin-left: 0 !important;
	}
</style>